import datetime
import tts
import pyautogui
import webbrowser
from num2words import num2words
import random
import customtkinter as CTk
import hashlib
import os
import time
import win32com.client as win32
import smtplib


def mute():
    pyautogui.press('volumemute')

def system_E(main_window):
    delay = 0.5

    pyautogui.hotkey('win', 'e')
    time.sleep(delay)

    image_path = "images/e_drive_icon.png"
    location = pyautogui.locateOnScreen(image_path, confidence=0.9)

    if location:
        pyautogui.doubleClick(location.left + location.width / 2, location.top + location.height / 2)
        time.sleep(delay)
        tts.va_speak("Диск E: открыт", main_window)

    else:
        tts.va_speak("Не удалось найти диск в проводнике", main_window)

def create_file(main_window):
    delay = 0.5
    time.sleep(delay)
    file_name = "/отчет.docx"
    tts.va_speak(f"Какое имя файла", main_window)
    time.sleep(2)
    main_window._insert_message("Отчет", "Вы")
    file_path = os.path.join(r"E:", file_name)
    with open(file_path, "w") as f:
        f.write("")

    time.sleep(delay)
    tts.va_speak(f"Файл '{file_name}' создан", main_window)

file_name = "/отчет.docx"
file_path = os.path.join(r"E:", file_name)
def edit_doc(main_window):
    word = win32.Dispatch('Word.Application')
    word.Visible = True

    tts.va_speak(f"Файл '{file_name}' открыт", main_window)

    doc = word.Documents.Open(file_path)
    time.sleep(4)
    main_window._insert_message("Добавь скриншот", "Вы")

    doc.InlineShapes.AddPicture(r"C:\Users\Iren\OneDrive\Рабочий стол\20_СБК_Мартынова_ВКР_Код\cats.png")

    tts.va_speak(f"Рисунок добавлен", main_window)
    time.sleep(5)
    main_window._insert_message("Добавь текст: Милые котики", "Вы")

    text = "Милые котики"
    doc.Content.InsertAfter(text)
    tts.va_speak(f"Текст добавлен", main_window)

    time.sleep(3)
    main_window._insert_message("Сделай скриншот", "Вы")

    screen(main_window)
    time.sleep(3)
    main_window._insert_message("Добавь скриншот", "Вы")

    doc.InlineShapes.AddPicture(r"C:\Users\Iren\OneDrive\Рабочий стол\20_СБК_Мартынова_ВКР_Код\screenshot.png")
    tts.va_speak(f"Рисунок добавлен", main_window)

    main_window._insert_message("Сохрани файл", "Вы")
    time.sleep(4)

    doc.Save()
    word.Quit()
    tts.va_speak(f"Файл сохранен", main_window)


def create_emai(main_window):

    delay = 2
    time.sleep(3)

    location = pyautogui.locateOnScreen("images/cr_mail.png", confidence=0.9)
    if location:
        pyautogui.click(location.left + location.width / 2, location.top + location.height / 2)
        time.sleep(delay)
    tts.va_speak(f"Кому письмо", main_window)
    time.sleep(4)
    main_window._insert_message("Себе", "Вы")

    sender = pyautogui.locateOnScreen("images/to.png", confidence=0.9)
    if sender:
        pyautogui.click(sender.left + sender.width / 2, sender.top + sender.height / 2)
        pyautogui.sleep(3)
        sender1 = pyautogui.locateOnScreen("images/myself.png", confidence=0.6)
        pyautogui.click(sender1.left + sender1.width / 2, sender1.top + sender1.height / 2)
        time.sleep(delay)

    add = pyautogui.locateOnScreen("images/add.png", confidence=0.7)
    if add:
        tts.va_speak(f"Где файл", main_window)
        time.sleep(3)
        main_window._insert_message("Диск е", "Вы")
        pyautogui.click(add.left + add.width / 2, add.top + add.height / 2)
        image_path = "images/e_drive_icon.png"
        time.sleep(delay)
        location2 = pyautogui.locateOnScreen(image_path, confidence=0.9)
        pyautogui.click(location2.left + location2.width / 2, location2.top + location2.height / 2)
        time.sleep(delay)
        tts.va_speak(f"Какой файл", main_window)
        time.sleep(3)
        main_window._insert_message("Отчет", "Вы")
        fle = pyautogui.locateOnScreen("images/file.png", confidence=0.5)
        pyautogui.doubleClick((fle.left + fle.width / 2, fle.top + fle.height / 2))
        time.sleep(delay)


    tts.va_speak(f"Какая тема", main_window)
    time.sleep(3)
    main_window._insert_message("Отчет", "Вы")
    theme = pyautogui.locateOnScreen("images/theme.png", confidence=0.9)
    if theme:
        pyautogui.click(theme.left + theme.width / 2, theme.top + theme.height / 2)
        time.sleep(3)

        theme1 = pyautogui.locateOnScreen("images/ot.png", confidence=0.9)
        pyautogui.click(theme1.left + theme1.width / 2, theme1.top + theme1.height / 2)
        time.sleep(delay)
    main_window._insert_message("Отправь письмо", "Вы")

    send = pyautogui.locateOnScreen("images/send.png", confidence=0.9)
    pyautogui.click(send.left + send.width / 2, send.top + send.height / 2)
    time.sleep(delay)
    tts.va_speak(f"Письмо отправлено", main_window)

def screen(main_window):
    screen = pyautogui.screenshot('screenshot.png')
    tts.va_speak(f"Скриншот сделан", main_window)


def jokes(main_window):
    jokes = ['Программы без ошибок можно писать двумя способами, но работает только третий...',
             'девяносто девять ошибок в коде, девяносто девять ошибок в коде. Возьми-ка одну и пофикси её. сто двадцать семь ошибок в коде...',
             'Чтобы понять рекурсию, нужно сперва понять рекурсию...']
    tts.va_speak(random.choice(jokes), main_window)


def music_off(main_window):
    if (pyautogui.locateCenterOnScreen('images/stop.png')):
        x, y = pyautogui.locateCenterOnScreen('images/stop.png')
        pyautogui.moveTo(x, y, duration=0.1)
        pyautogui.leftClick()
    else:
        tts.va_speak('Музыка уже выключена', main_window)


def music_on(main_window):
    if (pyautogui.locateCenterOnScreen('images/start.png')):
        x, y = pyautogui.locateCenterOnScreen('images/start.png')
        pyautogui.moveTo(x, y, duration=0.1)
        pyautogui.leftClick()
    else:
        tts.va_speak('Музыка уже включена', main_window)


def music_next():
    x, y = pyautogui.locateCenterOnScreen('images/next.png')
    pyautogui.moveTo(x, y, duration=0.1)
    pyautogui.leftClick()


def music_prev():
    x, y = pyautogui.locateCenterOnScreen('images/prev.png')
    pyautogui.moveTo(x, y, duration=0.1)
    pyautogui.leftClick()


def music_like(main_window):
    if (pyautogui.locateCenterOnScreen('images/like.png')):
        x, y = pyautogui.locateCenterOnScreen('images/like.png')
        pyautogui.moveTo(x, y, duration=0.1)
        pyautogui.leftClick()
    else:
        tts.va_speak("Трек уже был сохранен !", main_window)


def wish_me(main_window):
    hour = int(datetime.datetime.now().hour)

    if hour >= 5 and hour < 12:
        tts.va_speak("Доброе утро!☀️", main_window)

    elif hour >= 12 and hour < 18:
        tts.va_speak("Добрый день!🌞", main_window)
    elif hour >= 18 and hour < 23:
        tts.va_speak("Добрый вечер!🌆", main_window)
    else:
        tts.va_speak("Доброй ночи!🌙", main_window)
    tts.va_speak("Слушаю вас.", main_window)


def dtme(main_window):
    now = datetime.datetime.now()
    text = "Сейч+ас " + num2words(now.hour, lang='ru') + " " + num2words(now.minute, lang='ru')
    tts.va_speak(text, main_window)


def help(main_window):
    text = "Я умею:..."
    text += "подсказывать время..."
    text += "рассказывать анекдоты..."
    text += "включать и выключать звук компьютера..."
    text += "и открывать браузер, ютуб и яндекс музыку..."
    tts.va_speak(text, main_window)
    print(text)
